import os
import re
import shutil
import sys
import platform

g_version = '1.1'
g_modman_dir_name = ".modman"
g_modman_file_name = "modman"
g_modman_language_file_name = ".modmanlang"
g_system = platform.system().lower()
g_path_ignore_case = True if g_system == 'windows' else False
g_script_path = sys.argv[0]
g_script_dir = os.path.dirname(g_script_path)


def relativepath(srcpath, destpath, ignorecase=False):
    srcpath_ary = re.sub(r'[\\/]+', '/', srcpath).rstrip('/').split('/')
    destpath_ary = re.sub(r'[\\/]+', '/', destpath).rstrip('/').split('/')
    minlen = len(destpath_ary) if len(srcpath_ary) > len (destpath_ary) else len(srcpath_ary)
    index = 0

    for i in range(0, minlen, 1):
        index = i
        left = srcpath_ary[i].lower() if ignorecase else srcpath_ary[i]
        right = destpath_ary[i].lower() if ignorecase else destpath_ary[i]
        if left != right:
            break

    if index == 0:
        return destpath

    srcpath_remainder = srcpath_ary[index:]
    destpath_remainder = destpath_ary[index:]
    return (('..' + os.path.sep) * len(srcpath_remainder)) + os.path.sep.join(destpath_remainder)


def standardpath(path):
    return re.sub(r'[\\/]+', '/', path).rstrip('/')


def wildcardtoregx(wildcard):
    escape_list = "(){}[]^$+|"
    wildcard = wildcard.replace('\\', '\\\\') \
        .replace('.', '\\.') \
        .replace('*', '.*') \
        .replace('?', '.')

    for char in escape_list:
        wildcard = wildcard.replace(char, '\\' + char)

    return '^' + wildcard + '$'


def ynConfirm(message):
    while True:
        c = input(message).lower()

        if c == 'n':
            exit()
        elif c == 'y':
            break


def removeDirTreeOrFile(path):
    if os.path.exists(path):
        if os.path.isfile(path):
            os.remove(path)
        elif g_system == 'windows':
            os.system('rd /s /q "' + path + '"')
        else:
            shutil.rmtree(path)


#
# 判断路径是否在某个路径执行
# 文件夹是否为子文件夹
#
def isSubDir(parent, sub):
    parent = standardpath(parent)
    sub = standardpath(sub)

    if len(parent) >= len(sub) or parent == sub:
        return False

    index = sub.find(parent)

    if index == -1 \
            or index != 0 \
            or sub[len(parent)] != '/':
        return False

    return True


def isSamePath(pathA, pathB):
    return standardpath(pathA) == standardpath(pathB)


def fileGetContent(path):
    if not os.path.exists(path):
        return ''

    file_object = open(path)

    try:
        all_the_text = file_object.read()
    except Exception:
        all_the_text = ''
    finally:
        file_object.close()

    return all_the_text


def filePutContent(path, content, isAppend=False):
    mode = 'a' if isAppend else 'w'

    fhandle = open(path, mode)
    result = len(content)

    try:
        fhandle.write(content)
    except Exception:
        result = False
    finally:
        fhandle.close()
        return result


def mergeAry(aryl, aryr):
    aryr_len = len(aryr)

    for i in range(aryr_len):
        if i >= len(aryl):
            aryl.append(aryr[i])
        else:
            aryl[i] = aryr[i]

    return aryl


def createEmptyListByLength(length):
    ary = []

    for i in range(length):
        ary.append('')

    return ary


def getTextArgn(text):
    text = re.sub('\{{2,}', '', text)
    length = len(re.findall('\{}', text))

    if length == 0:
        length = len(re.findall('\{([0-9]+)}', text))

    return length
